package com.cedifie.lendapp.ui.loan.fm

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Paint
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.cedifie.lendapp.R
import com.cedifie.lendapp.config.CedConfigs
import com.cedifie.lendapp.databinding.FmLoanCommonBinding
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.mvp.MvpFm
import com.cedifie.lendapp.ui.loan.adapter.CedLoanAccountAdapter
import com.cedifie.lendapp.ui.loan.impl.CedLoanCommonPresenterImpl
import com.cedifie.lendapp.ui.loan.view.ICedLoanCommonView
import com.cedifie.lendapp.ui.user.act.CedUserLoginAct
import com.cedifie.lendapp.utils.decoration.LinearSpacingItemDecoration
import com.cedifie.lendapp.utils.dialog.BindCardAddDialog
import com.cedifie.lendapp.utils.dialog.BindCardDeleteDialog
import com.cedifie.lendapp.utils.dialog.BindCardOnlyOneWarningDialog
import com.cedifie.lendapp.utils.dialog.BindCardOtherDialog
import com.cedifie.lendapp.utils.dialog.ClearDataDialog
import com.cedifie.lendapp.utils.event.CedEventType
import com.cedifie.lendapp.utils.helper.SharedHelper
import com.cedifie.lendapp.utils.status.StatusRepository
import com.lib.base.utils.DensityUtils
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject


/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/17 13:41
 * @Annotation：审核中、拒绝、放贷中、放贷中法语 Page
 */
class CedLoanCommonFm(): MvpFm<ICedLoanCommonView, CedLoanCommonPresenterImpl>(),ICedLoanCommonView {
    private var _binding: FmLoanCommonBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "binding is null"
    )

    var data: JSONObject? = null

    //账户列表
    private var accountAdapter: CedLoanAccountAdapter? = null
    //只有一个收款账户提示
    var onlyOneWarningDialog: BindCardOnlyOneWarningDialog? = null

    constructor(data: JSONObject): this(){
        this.data = data
    }

    override fun getCedRootView(inflater: LayoutInflater): View {
        _binding = FmLoanCommonBinding.inflate(inflater)
        return binding.root
    }

    override fun initCedView() {
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#00000000"))
        initCedRefreshLayout()
        initCedAccountRecyclerView()

        //默认先不显示失败样式
        _binding?.failedLayout?.visibility = View.GONE
        _binding?.clearDataLayout?.visibility = View.GONE
        _binding?.tvClearData?.paint?.flags = Paint.UNDERLINE_TEXT_FLAG//下划线
        _binding?.tvClearData?.paint?.isAntiAlias = true//抗锯齿
    }

    override fun initCedListener() {
        //刷新
        _binding?.imgStatusRefresh?.setOnClickListener {
            showCedLoading(getString(R.string.loading))
            //发送刷新流程通知
            EventBus.getDefault().post(CedEventType.NOTICE.CED_PROCESS_REFRESH)
        }
        //添加绑卡
        _binding?.addAccountLayout?.setOnClickListener {
            showCedBindCardDialog()
        }
        //清除用户数据
        _binding?.clearDataLayout?.setOnClickListener {
            showCedClearUserDataDialog()
        }
    }

    override fun initCedData() {
        data?.let {
            mvpPresenter?.checkCedOrderOrApplyStatusAction(it)
            HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_LOAN_COMMON_START,it.optString("eventRemark"))
        }
    }

    override fun createMvpPresenter(): CedLoanCommonPresenterImpl {
        return CedLoanCommonPresenterImpl(context)
    }

    /* 初始化刷新 */
    private fun initCedRefreshLayout() {
        //禁止加载
        _binding?.refreshLayout?.setEnableLoadMore(false)
        _binding?.refreshLayout?.setEnableAutoLoadMore(false)
        _binding?.refreshLayout?.setOnRefreshListener {
            //发送刷新流程通知
            EventBus.getDefault().post(CedEventType.NOTICE.CED_PROCESS_REFRESH)
        }
        _binding?.refreshLayout?.setOnLoadMoreListener {
            _binding?.refreshLayout?.finishLoadMore()
        }
    }

    /**
     * 初始化账户列表
     */
    private fun initCedAccountRecyclerView() {
        _binding?.rvAccount?.setHasFixedSize(true)
        _binding?.rvAccount?.isNestedScrollingEnabled = false
        _binding?.rvAccount?.isFocusableInTouchMode = false //不需要焦点
        _binding?.rvAccount?.layoutManager = LinearLayoutManager(context)
        val topDecoration = DensityUtils.dp2px(12f)
        _binding?.rvAccount?.addItemDecoration(LinearSpacingItemDecoration(0,0,topDecoration,topDecoration))
        accountAdapter = CedLoanAccountAdapter(_binding?.rvAccount)
        _binding?.rvAccount?.adapter = accountAdapter
        _binding?.rvAccount?.itemAnimator = DefaultItemAnimator()
        accountAdapter?.setOnItemChildClickListener { _, childView, position ->
            when(childView.id){
                R.id.btnDelete -> {//删除
                    showCedDeleteDialog(position)
                }
            }
        }
    }

    /**
     * 状态改变，需要刷新页面
     */
    fun refreshView(data: JSONObject){
        this.data = data
        mvpPresenter?.checkCedOrderOrApplyStatusAction(data)
//        mvpPresenter?.loadCedLoanInfoAction()
//        loadAccountListAction()
//        loadRecommendAppAction()
    }

    /**
     * 显示放款中状态
     */
    override fun showCedLoanLendingView() {
        mvpPresenter?.loadCedLoanInfoAction()

        _binding?.statusTipsLayout?.setBackgroundResource(R.drawable.ced_loan_success_tips_bg)
        _binding?.imgStatusLable?.setImageResource(R.mipmap.icon_loan_success_tips_lable)
        _binding?.textStatusTips?.text = getString(R.string.loan_common_success_tips)
        _binding?.textStatusTips?.setTextColor(Color.parseColor("#FF00CE90"))
        _binding?.textStatusTipsDes?.text = getString(R.string.loan_common_success_tips_des)
    }

    /**
     * 显示审核中状态
     */
    override fun showCedLoanAuditView() {
        mvpPresenter?.loadCedLoanInfoAction()

        _binding?.statusTipsLayout?.setBackgroundResource(R.drawable.ced_loan_audit_tips_bg)
        _binding?.imgStatusLable?.setImageResource(R.mipmap.icon_loan_audit_tips_lable)
        _binding?.textStatusTips?.text = getString(R.string.loan_common_audit_tips)
        _binding?.textStatusTips?.setTextColor(Color.parseColor("#FF2E86F6"))
        _binding?.textStatusTipsDes?.text = getString(R.string.loan_common_audit_tips_des)
    }

    /**
     * 已拒绝（审核失败）
     */
    override fun showCedLoanFailedView() {
        _binding?.textApplyAgain?.text = String.format(getString(R.string.loan_common_failed_tips_des),data?.optString("againApplyDate"))
        mvpPresenter?.checkClearUserDataAction(true)

        _binding?.failedLayout?.visibility = View.VISIBLE
        _binding?.loanInfoLayout?.visibility = View.GONE
        _binding?.textReceiveAccountTitle?.visibility = View.GONE
        _binding?.textReceiveAccountDes?.visibility = View.GONE
        _binding?.rvAccount?.visibility = View.GONE
        _binding?.addAccountLayout?.visibility = View.GONE

    }

    /**
     * 设置贷款信息
     */
    @SuppressLint("SetTextI18n")
    override fun showCedLoanInfoData(data: JSONObject) {
        _binding?.textAmount?.text = "${data.optString("currency")} ${data.optString("amount")}"
        _binding?.textDays?.text = String.format(requireContext().getString(R.string.loan_apply_loan_term_days),data.optString("days"))

        _binding?.failedLayout?.visibility = View.GONE
        _binding?.clearDataLayout?.visibility = View.GONE
        _binding?.loanInfoLayout?.visibility = View.VISIBLE
        _binding?.textReceiveAccountTitle?.visibility = View.VISIBLE
        _binding?.textReceiveAccountDes?.visibility = View.VISIBLE
        _binding?.rvAccount?.visibility = View.VISIBLE
        _binding?.addAccountLayout?.visibility = View.VISIBLE
        //只有法语地区才显示添加账号按钮
        if (!CedConfigs.isFrench()){
            _binding?.addAccountLayout?.visibility = View.GONE
        }
    }

    /**
     * 设置已绑定的账户列表
     */
    override fun showCedLoanAccountList(accountList: ArrayList<JSONObject>) {
        accountAdapter?.data = accountList
        /**
         * 法语地区 审核中 && 只有一个账户  提示新增绑卡
         */
        if (CedConfigs.isFrench() && data != null){
            //申请状态
            val applyStatus = data?.optString("applyStatus")
            //审核中 && 只有一个账户
            if (StatusRepository(applyStatus).isReviewing() && accountList.size <= 1){
                showCedAccountOnlyOneAddDialog()
            }
        }
    }

    /**
     * 是否显示清除数据按钮
     */
    override fun showCedClearUserDataButton(isShow: Boolean) {
        if (isShow){
            _binding?.clearDataLayout?.visibility = View.VISIBLE
        } else {
            _binding?.clearDataLayout?.visibility = View.GONE
        }
    }

    /**
     * 清除用户数据成功
     */
    override fun showCedClearUserDataSuccess() {
        //移除已登录状态
        SharedHelper.onCedLoginOut()
        Handler(Looper.getMainLooper()).postDelayed({
            onIntent(CedUserLoginAct::class.java)
        },300)
    }

    /**
     * 法语地区 审核中 && 只有一个账户  提示新增绑卡
     */
    private fun showCedAccountOnlyOneAddDialog() {
        if (onlyOneWarningDialog == null){
            onlyOneWarningDialog = BindCardOnlyOneWarningDialog(requireContext(),object : BindCardOnlyOneWarningDialog.IDialogCallback{
                override fun onClick(view: View?) {
                    if (view?.id == R.id.btnAdd){
                        showCedBindCardDialog()
                    }
                }
            })
            onlyOneWarningDialog?.setCancelable(true)
            onlyOneWarningDialog?.setCanceledOnTouchOutside(false)
        }
        onlyOneWarningDialog?.let {
            if (it.isShowing){
                return
            }
            it.show()
        }
    }

    /**
     * 添加绑卡dialog
     */
    private fun showCedBindCardDialog(){
        data?.let {
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_USER_ACCOUNT_ADD,it.optString("eventRemark"))
        }
        val bindCardDialog = BindCardAddDialog(context,"StepAccount Page",object : BindCardAddDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
            override fun onSubmitParams(typeObj: JSONObject, phoneNumber: String) {
                mvpPresenter?.submitCedBindAccountAction(phoneNumber,typeObj.optString("value"))
            }
        })
        bindCardDialog.setCancelable(true)
        bindCardDialog.setCanceledOnTouchOutside(false)
        bindCardDialog.show()
    }

    /**
     * 提示绑定另一个渠道账户
     */
    override fun showCedBingAccountOtherDialog(otherInfo: JSONObject) {
        data?.let {
            val replaceDialog = BindCardOtherDialog(context,it.optString("eventRemark"),object : BindCardOtherDialog.IDialogCallback{
                override fun onClick(view: View?) {
                    if (view?.id == R.id.btnRight){//添加
                        mvpPresenter?.submitCedBindAccountAction(otherInfo.optString("walletMobile"),otherInfo.optString("value"), "YES")
                    }
                }
            })
            replaceDialog.setCancelable(true)
            replaceDialog.setCanceledOnTouchOutside(false)
            replaceDialog.show()
            replaceDialog.setBindAccountInfo(otherInfo)
        }
    }

    /**
     * 删除提示
     */
    private fun showCedDeleteDialog(position: Int){
        accountAdapter?.let {
            val item = it.getItem(position)
            item.put("walletLogo",item.optString("logo"))
            item.put("walletDesc",item.optString("name"))
            item.put("walletMobile",item.optString("account"))
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_USER_ACCOUNT_DELETE,item.optString("cardId"))
            val deleteDialog = BindCardDeleteDialog(context,"StepAccount Page", object : BindCardDeleteDialog.IDialogCallback{
                override fun onClick(view: View?) {
                    if (view?.id == R.id.btnRight){
                        mvpPresenter?.deleteCedAccountAction(item.optString("cardId"))
                    }
                }
            })
            deleteDialog.setCancelable(true)
            deleteDialog.setCanceledOnTouchOutside(false)
            deleteDialog.show()
            deleteDialog.setBindAccountInfo(item)
        }
    }

    /**
     * 清除用户数据提示
     */
    private fun showCedClearUserDataDialog(){
        val dialog = ClearDataDialog(context,"Loan Rejected Page",object : ClearDataDialog.IDialogCallback{
            override fun onClick(view: View?) {
                mvpPresenter?.checkClearUserDataAction(false)
            }
        })
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
    }

    override fun hideCedLoading() {
        super.hideCedLoading()
        _binding?.refreshLayout?.finishRefresh()
    }

    override fun onDestroy() {
        super.onDestroy()
        data?.let {
            HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_LOAN_COMMON_END,it.optString("eventRemark"))
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}